<!--
 * @Description: 
 * @Author: 张文韬
 * @Date: 2022-09-06 14:09:26
 * @LastEditTime: 2024-07-16 13:50:29
 * @LastEditors: 张文韬
 * @Reference: 
-->
<template>
  <div>
    <DefaultTableList
      ref="tableListRef"
      :loadMethod="searchOrder"
      :formOptions="searchOptions"
      :beforeLoad="beforeLoad"
      :btns="btns"
      :controlEvents="{ output }"
      :tableConfig="columns">
      <template #left>
        <!-- <div>标准总计：<span text-red font-bold>{{ 6225 }}</span> 元， 实收总计：<span text-red font-bold>{{ 4873.8 }}</span> 元</div> -->
      </template>
      <template #status="{ scope }">
				<dict-tag :options="order_status" :value="scope.row.orderStatus"></dict-tag>
			</template>
      <template #handleSlot="{ scope }">
        <el-button
          type="primary"
          link
          size="small"
          @click="detail(scope.row)"
        >详情</el-button>
        <!-- <el-button
          v-if="scope.row.orderStatus == 1"
          type="primary"
          link
          size="small"
          @click="downloadOrder(scope.row)"
        >保单</el-button> -->
        <el-button
          v-if="scope.row.policyStatus == 2 && scope.row.orderStatus == 0"
          type="success"
          link
          size="small"
          @click="pay(scope.row)"
        >付款</el-button>
        <el-button
          v-if="scope.row.policyStatus == 2"
          type="danger"
          link
          size="small"
          @click="cancel(scope.row)"
        >撤单</el-button>
        <el-button
          v-if="scope.row.policyStatus != 2"
          type="success"
          link
          size="small"
          @click="reboot(scope.row)"
        >重投</el-button>
        <el-button
          v-if="scope.row.policyStatus == 2 && scope.row.invoiceFlag == 0"
          type="success"
          link
          size="small"
          @click="handleGetInvoice(scope.row)"
        >申请发票</el-button>
        <el-button
          v-if="scope.row.invoiceFlag == 2"
          type="primary"
          link
          size="small"
          @click="handleDownloadInvoice(scope.row)"
        >查看发票</el-button>
      </template>
    </DefaultTableList>
    <el-dialog
      v-model="dialogShow"
      title="订单明细"
      :width="1000"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <OrderDetail v-if="dialogShow" ref="orderDetailRef" :data="dialogFormCurrent" />
      <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleCopy"> 复制名单 </el-button>
        <el-button @click="handleCancel">关闭</el-button>
      </div>
    </template>
    </el-dialog>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import { formOptions, btns } from './control'
import columns from './columns'
import DefaultTableList from '@/components/DefaultTableList/index.vue'
import OrderDetail from '../../components/OrderDetail/index.vue'
import handleClipboard from '@/utils/clipboard';
import { getBirth, getSex } from '@/utils/id-card'
import { searchOrder, bbOrderCancel, getPayUrl, getItem, asyncCreateFinanceInvoice } from '@/api/insurance'
import { useDict } from '/@/hooks/dict';
import { downBlobFile } from '/@/utils/other';
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';

const { order_status, insurance_company } = useDict('order_status', 'insurance_company');

const router = useRouter()

const tableListRef = ref()

const searchOptions = reactive(formOptions);
const loadData = async () => {
	searchOptions.forEach((item) => {
		if (item.key == 'orderStatus') {
			item.options = order_status;
		} else if (item.key == 'companyId') {
			item.options = insurance_company;
		}
	});
};
loadData();

// buttom config --------------------------------------------------------------
// const insert = () => {}

// const handleClick = (index, row) => {
//   console.log(index, row)
//   if (index == 0) {
//     detail(row)
//   } else if (index == 1) {
//     downloadOrder(row)
//   } else if (index == 3) {
//     cancel(row)
//   }
// }
const beforeLoad = (params) => { 
  const { dateRange } = params
  return {
    startDate: dateRange && dateRange.length > 0 ? dateRange[0] + ' 00:00:00' : '',
    endDate: dateRange && dateRange.length > 0 ? dateRange[1] + ' 23:59:59' : '',
    ...params
  }
}

const dialogShow = ref(false)
const dialogFormCurrent = ref({})
const detail = async (row) => {
  const { data } = await getItem({ id: row.id })
  dialogFormCurrent.value = { 
    ...data,
    ...data.insureBase,
    ...data.applicantInfo,
  }
  openDialog()
}

const downloadOrder = (row) => {
  downBlobFile('/api/bbOrder/insurancePolicy', { id: row.id }, `${row.name}.pdf`, 'post')
}

const cancel = async (row) => {
  ElMessageBox.confirm('确认取消该订单吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await bbOrderCancel({ id: row.id })
		ElMessage.success('操作成功');
		tableListRef.value.reload();
	});
  
}

const reboot = async (row) => {
  ElMessageBox.confirm('确认要重投该订单吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		router.push({
      path: '/insurance/insurances/input/index',
      query: {
        id: row.id,
        mode: 'reboot'
      }
    })
	});
}

const pay = (row) => {
  ElMessageBox.confirm('确认要支付该订单吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
    const { data: { payUrl, orderStatus, payChannelMsg } } = await getPayUrl({
      id: row.id
    })
    if (orderStatus == 1) {
      ElMessage.success(payChannelMsg)
    } else if (payUrl) {
      window.location.href = payUrl
    }
	});
}

const handleGetInvoice = async (row) => {
  ElMessageBox.confirm('确认要申请发票吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
    await asyncCreateFinanceInvoice({
      id: row.id
    })
    ElMessage.success('操作成功')
    tableListRef.value.reload()
	});
}

const handleDownloadInvoice = async (row) => {
  if (row.invoice && row.invoice.invoicePdfUrl) {
    window.open(row.invoice.invoicePdfUrl, '_blank')
  } else {
    ElMessage.error('未获取到发票信息')
  }
  // const { data } = await asyncCreateFinanceInvoice({
  //   id: row.id
  // })
  // downBlobFile('/api/bbOrder/invoice', { id: row.id }, `${row.name}.pdf`, 'post')
}

const output = () => {
	tableListRef.value.export('订单信息.xlsx', '/api/bbOrder/exportImpl');
};

const openDialog = (type = 'insurant-insert') => {
  // dialogType.value = type
  dialogShow.value = true
}

const closeDialog = () => {
  dialogShow.value = false
}

const handleCancel = () => {
  closeDialog()
  dialogFormCurrent.value = null
}

const orderDetailRef = ref(null)
const handleCopy = () => {
  const data = orderDetailRef.value.getTableData()
  let str = ''
  if (data && data.length > 0) {
    str = data.map(o => `${o.name} ${o.gender} ${o.certificateNo} ${o.birthday}`).join('\n')
    handleClipboard(str)
  }
}

</script>
